<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12" md="6" class="d-flex justify-end align-center">
        <v-btn
          color="primary"
          prepend-icon="mdi-plus"
          @click="openUserDialog()"
        >
          添加用户
        </v-btn>
      </v-col>
    </v-row>

    <!-- 筛选和搜索 -->
    <v-row class="mb-6">
      <v-col cols="12" md="3">
        <v-select
          v-model="selectedRole"
          :items="roleOptions"
          label="筛选角色"
          variant="filled"
          density="comfortable"
          clearable
          @update:model-value="loadUsers"
        ></v-select>
      </v-col>
      <v-col cols="12" md="9">
        <v-text-field
          v-model="searchText"
          prepend-inner-icon="mdi-magnify"
          label="搜索用户名、姓名或电话"
          variant="filled"
          density="comfortable"
          clearable
        ></v-text-field>
      </v-col>
    </v-row>

    <!-- 用户列表 -->
    <v-card>
      <v-card-text>
        <!-- 移动端完整视图 -->
        <div v-if="mobile" class="mobile-user-list">
          <v-card
            v-for="user in paginatedMobileUsers"
            :key="user.id"
            class="mb-3"
            variant="outlined"
          >
            <v-card-text class="pa-2">
              <!-- 头部信息：ID、姓名、用户名、角色、电话 -->
              <div class="d-flex align-center mb-2">
                <v-avatar :color="getRoleColor(user.role)" size="32" class="me-2">
                  <span class="text-white text-caption">{{ user.name.charAt(0) }}</span>
                </v-avatar>
                <div class="flex-grow-1">
                  <div class="d-flex align-center justify-space-between">
                    <div>
                      <div class="font-weight-medium text-body-2">{{ user.name }} <span class="text-caption text-medium-emphasis">(ID: {{ user.id }})</span></div>
                      <div class="text-caption text-medium-emphasis">{{ user.username }}</div>
                    </div>
                    <div class="d-flex align-center gap-1">
                      <v-chip :color="getRoleColor(user.role)" size="x-small" variant="elevated">
                        {{ getRoleText(user.role) }}
                      </v-chip>
                      <div v-if="user.phone" class="d-flex align-center">
                        <v-icon size="12" class="me-1" color="medium-emphasis">mdi-phone</v-icon>
                        <a :href="`tel:${user.phone}`" class="text-caption text-decoration-none text-medium-emphasis">
                          {{ user.phone }}
                        </a>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 操作按钮 -->
              <div class="d-flex justify-end gap-1">
                <v-btn
                  size="small"
                  variant="outlined"
                  color="primary"
                  icon="mdi-pencil"
                  @click="openUserDialog(user)"
                ></v-btn>
                <v-btn
                  size="small"
                  variant="outlined"
                  color="error"
                  icon="mdi-delete"
                  @click="deleteUser(user)"
                  :disabled="user.role === 'admin'"
                ></v-btn>
              </div>
            </v-card-text>
          </v-card>
          
          <!-- 移动端分页 -->
          <div class="d-flex justify-center mt-4">
            <v-pagination
              v-model="mobilePage"
              :length="mobilePageCount"
              :total-visible="5"
              size="small"
            ></v-pagination>
          </div>
        </div>

        <!-- 桌面端数据表格 -->
        <v-data-table
          v-else
          :headers="headers"
          :items="filteredUsers"
          :loading="loading"
          class="elevation-1"
          :items-per-page="10"
        >
          <template v-slot:item.username="{ item }">
            <div class="d-flex align-center">
              <v-avatar :color="getRoleColor(item.role)" size="40" class="me-3">
                <span class="text-white">{{ item.name.charAt(0) }}</span>
              </v-avatar>
              <div>
                <div class="font-weight-medium">{{ item.name }}</div>
                <div class="text-caption text-medium-emphasis">{{ item.username }}</div>
              </div>
            </div>
          </template>

          <template v-slot:item.role="{ item }">
            <v-chip
              :color="getRoleColor(item.role)"
              size="small"
              variant="elevated"
            >
              {{ getRoleText(item.role) }}
            </v-chip>
          </template>

          <template v-slot:item.contact="{ item }">
            <div>
              <div v-if="item.phone" class="d-flex align-center mb-1">
                <v-icon size="16" class="me-2">mdi-phone</v-icon>
                <a :href="`tel:${item.phone}`" class="text-decoration-none">
                  {{ item.phone }}
                </a>
              </div>

            </div>
          </template>

          <template v-slot:item.created_at="{ item }">
            {{ formatDate(item.created_at) }}
          </template>

          <template v-slot:item.actions="{ item }">
            <v-btn
              icon
              size="small"
              variant="text"
              @click="openUserDialog(item)"
            >
              <v-icon>mdi-pencil</v-icon>
            </v-btn>
            

            
            <v-btn
              icon
              size="small"
              variant="text"
              color="error"
              @click="deleteUser(item)"
              :disabled="item.role === 'admin'"
            >
              <v-icon>mdi-delete</v-icon>
            </v-btn>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- 用户编辑对话框 -->
    <v-dialog v-model="userDialog" max-width="600">
      <v-card>
        <v-card-title>
          {{ editingUser?.id ? '编辑用户' : '添加用户' }}
        </v-card-title>
        
        <v-card-text>
          <v-form ref="userFormRef" @submit.prevent="saveUser">
            <v-row>
              <v-col cols="12" sm="6">
                <v-text-field
                  v-model="userForm.username"
                  label="用户名"
                  variant="filled"
                  density="comfortable"
                  :rules="usernameRules"
                  :disabled="!!editingUser?.id"
                  required
                ></v-text-field>
              </v-col>
              <v-col cols="12" sm="6" v-if="!editingUser?.id">
                <v-text-field
                  v-model="userForm.password"
                  label="密码"
                  type="password"
                  variant="filled"
                  density="comfortable"
                  :rules="passwordRules"
                  required
                ></v-text-field>
              </v-col>
              <v-col cols="12" sm="6">
                <v-text-field
                  v-model="userForm.name"
                  label="姓名"
                  variant="filled"
                  density="comfortable"
                  :rules="nameRules"
                  required
                ></v-text-field>
              </v-col>
              <v-col cols="12" sm="6">
                <v-select
                  v-model="userForm.role"
                  :items="roleOptions"
                  label="角色"
                  variant="filled"
                  density="comfortable"
                  :rules="roleRules"
                  required
                ></v-select>
              </v-col>
              <v-col cols="12" sm="6">
                <v-text-field
                  v-model="userForm.phone"
                  label="手机号"
                  variant="filled"
                  density="comfortable"
                  :rules="phoneRules"
                ></v-text-field>
              </v-col>

            </v-row>
          </v-form>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="userDialog = false">取消</v-btn>
          <v-btn color="primary" @click="saveUser" :loading="saving">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>




  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useDisplay } from 'vuetify'
import api from '@/utils/api'

const { mobile } = useDisplay()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const users = ref([])
const searchText = ref('')
const selectedRole = ref('')
const userDialog = ref(false)
const editingUser = ref(null)
const mobilePage = ref(1)
const mobileItemsPerPage = ref(10)

const userForm = ref({
  username: '',
  password: '',
  name: '',
  role: '',
  phone: ''
})

const userFormRef = ref(null)

// 表格标题
const headers = [
  { title: 'ID', key: 'id', sortable: true },
  { title: '用户信息', key: 'username', sortable: true },
  { title: '角色', key: 'role', sortable: true },
  { title: '联系方式', key: 'contact', sortable: false },
  { title: '操作', key: 'actions', sortable: false }
]

// 角色选项
const roleOptions = [
  { title: '管理员', value: 'admin' },
  { title: '教师', value: 'teacher' },
  { title: '司机', value: 'driver' },
  { title: '课后教师', value: 'after_school_teacher' }
]

// 计算属性
const filteredUsers = computed(() => {
  let result = users.value
  
  if (selectedRole.value) {
    result = result.filter(user => user.role === selectedRole.value)
  }
  
  if (searchText.value) {
    const search = searchText.value.toLowerCase()
    result = result.filter(user => 
      user.name.toLowerCase().includes(search) ||
      user.username.toLowerCase().includes(search) ||
      user.phone?.toLowerCase().includes(search)
    )
  }
  
  return result
})

const mobilePageCount = computed(() => {
  return Math.ceil(filteredUsers.value.length / mobileItemsPerPage.value)
})

const paginatedMobileUsers = computed(() => {
  const start = (mobilePage.value - 1) * mobileItemsPerPage.value
  const end = start + mobileItemsPerPage.value
  return filteredUsers.value.slice(start, end)
})

// 验证规则
const usernameRules = [
  v => !!v || '用户名不能为空',
  v => v.length >= 3 || '用户名至少3位',
  v => /^[a-zA-Z0-9_]+$/.test(v) || '用户名只能包含字母、数字和下划线'
]

const passwordRules = [
  v => !!v || '密码不能为空',
  v => v.length >= 6 || '密码至少6位'
]

const nameRules = [
  v => !!v || '姓名不能为空',
  v => v.length >= 2 || '姓名至少2个字符'
]

const roleRules = [
  v => !!v || '请选择角色'
]

const phoneRules = [
  v => !v || /^1[3-9]\d{9}$/.test(v) || '请输入正确的手机号'
]



// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    const params = selectedRole.value ? { role: selectedRole.value } : {}
    const response = await api.get('/users', { params })
    users.value = response.data.data.users
  } catch (error) {
    console.error('加载用户列表失败:', error)
    window.showNotification?.('加载用户列表失败', 'error')
  } finally {
    loading.value = false
  }
}

const openUserDialog = (user = null) => {
  editingUser.value = user
  if (user) {
    Object.assign(userForm.value, {
      username: user.username,
      password: '',
      name: user.name,
      role: user.role,
      phone: user.phone || ''
    })
  } else {
    Object.assign(userForm.value, {
      username: '',
      password: '',
      name: '',
      role: '',
      phone: ''
    })
  }
  userDialog.value = true
}

const saveUser = async () => {
  if (!userFormRef.value) return
  const { valid } = await userFormRef.value.validate()
  if (!valid) return
  
  saving.value = true
  try {
    if (editingUser.value?.id) {
      // 更新用户 - 移除密码和用户名字段
      const { password, username, ...updateData } = userForm.value
      await api.put(`/users/${editingUser.value.id}`, updateData)
      window.showNotification?.('用户信息更新成功', 'success')
    } else {
      // 创建用户
      await api.post('/users', userForm.value)
      window.showNotification?.('用户添加成功', 'success')
    }
    
    userDialog.value = false
    loadUsers()
    
  } catch (error) {
    console.error('保存用户失败:', error)
    const message = error.response?.data?.message || '保存用户失败'
    window.showNotification?.(message, 'error')
  } finally {
    saving.value = false
  }
}



const deleteUser = async (user) => {
  if (!confirm(`确定要删除用户 "${user.name}" 吗？\n删除后该用户将无法登录系统。`)) return
  
  try {
    await api.delete(`/users/${user.id}`)
    loadUsers()
    window.showNotification?.('用户删除成功', 'success')
  } catch (error) {
    console.error('删除用户失败:', error)
    const message = error.response?.data?.message || '删除用户失败'
    window.showNotification?.(message, 'error')
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const getRoleColor = (role) => {
  const colorMap = {
    admin: 'red',
    teacher: 'blue',
    driver: 'green',
    after_school_teacher: 'orange'
  }
  return colorMap[role] || 'grey'
}

const getRoleText = (role) => {
  const textMap = {
    admin: '管理员',
    teacher: '教师',
    driver: '司机',
    after_school_teacher: '课后教师'
  }
  return textMap[role] || role
}

// 生命周期
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.v-data-table {
  border-radius: 8px;
}

.text-decoration-none {
  text-decoration: none;
  color: inherit;
}

.text-decoration-none:hover {
  text-decoration: underline;
}
</style>
